<template>
    <div class="bookcontent">
        <!-- <LazyLoading :content="ChapterList"></LazyLoading> -->
        <div class="isShowPopup" @click="toggleShow" ref="bookbox">
            <div class="item-box" v-for="(item, index) in BookContent" :key="index" v-show="BookContent !== null">
                <div class="item" v-html="item" ref="item"></div>
            </div>
        </div>

        <!-- 顶部弹出层 -->
        <van-popup v-model="show" position="top" :style="{ height: '6%' }">
            <div class="Toptool">
                <van-icon name="arrow-left" class="arrow-left" @click="Back()" />
            </div>
        </van-popup>

        <!-- 目录弹出框 -->
        <van-popup class="catalogue-box" v-model="leftshow" position="left" :style="{ height: '100%', width: '80%' }">
            <div class="TopMsg" v-if="BookMsg !== null" v-for="(item, index) in BookMsg">
                <div class="top">
                    <!-- 书籍图片 -->
                    <div class="BookCover">
                        <img class="img-auto" :src="item.coverImage" />
                    </div>
                    <!-- 书籍名字以及作者 -->
                    <div class="name-author">
                        <div class="name">{{ item.title }}</div>
                        <div class="author">{{ item.author }}</div>
                    </div>
                </div>
                <div class="bottom">
                    <div class="totalChapterQuantity">共{{ totalChapterQuantity }}章</div>
                    <!-- 正序倒序 -->
                    <div class="reverse" @click="overturn" v-if="reverseflag">
                        倒序
                        <van-icon name="arrow-up" />
                    </div>
                    <div class="reverse" @click="overturn" v-else>
                        正序
                        <van-icon name="arrow-down" />
                    </div>
                </div>
            </div>
            <!-- 具体章节 -->
            <div class="ShowCatalogue">
                <div class="Catalogue-item" v-for="(item, index) in ChapterList" :key="index" @click="getuuid(BookId, item.uuid, item.needPay)">
                    {{ item.title }}
                    <!-- <div class="pay" v-if="item.needPay"> -->
                    <div v-if="item.needPay">
                        <van-icon name="lock" />
                    </div>
                </div>
            </div>
        </van-popup>
        <!-- 分享弹出层 -->
        <van-share-sheet v-model="showShare" title="立即分享给好友" :options="options" :overlay="true" />
        <!-- 更多 -->
        <van-popup v-model="moreShow" position="bottom" :style="{ height: 'auto' }">
            <div class="share" @click="showshare()">分享书籍</div>
        </van-popup>
        <!-- 底部弹出层 -->
        <van-popup v-model="show" position="bottom" :style="{ height: '20%' }" :overlay="false">
            <div class="bottomtool">
                <p class="CurrentChapter">{{ currentTitle }}</p>
                <!-- 上下章和进度条 -->
                <div class="progress-box">
                    <van-icon name="arrow-left" class="left" @click="previousChapter" />
                    <van-slider v-model="value" class="slider" />
                    <van-icon name="arrow" class="right" @click="nextTChapter" />
                </div>
                <!-- 其他操作 -->
                <div class="operation">
                    <!-- 弹出目录 -->
                    <div class="Catalogue-box">
                        <img src="../assets/images/mulu.png" />
                        <div class="text" @click="PopupCatalogue">目录</div>
                    </div>

                    <!-- 字体大小 -->
                    <div class="Font-box" @click="setSize">
                        <img src="../assets/images/font-size.png" />
                        <div class="text">设置</div>
                    </div>
                    <!-- 夜间/日间 -->
                    <div class="Pattern-box" @click="toggleModel" v-if="moduleFlag">
                        <img src="../assets/images/background-day.png" />
                        <div class="text">日间</div>
                    </div>
                    <div class="Pattern-box" @click="toggleModel" v-else>
                        <img src="../assets/images/background-night.png" />
                        <div class="text">夜间</div>
                    </div>

                    <!-- 更多 -->
                    <div class="More-box" @click="more">
                        <img src="../assets/images/MoreOperation.png" />
                        <div class="text">更多</div>
                    </div>
                </div>
            </div>
        </van-popup>
        <!-- 字体大小弹窗 -->
        <van-popup class="setFontSize" v-model="fontsizeShow" position="bottom" :style="{ height: '10%' }">
            <div class="title">字体大小:</div>
            <div class="set">
                <div class="minus" @click="minishSize">A-</div>
                <div class="text">{{ fontSizeDesc }}</div>
                <div class="augment" @click="augmentSize">A+</div>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { Toast } from "vant";

import LazyLoading from "../components/LazyLoading.vue";
export default {
    name: "BookContent",
    data() {
        return {
            show: false,
            // 目录
            leftshow: false,
            // 字体大小弹窗
            fontsizeShow: false,
            // 滑块值
            value: 10,
            // 书籍id
            BookId: null,
            // 书籍信息
            BookMsg: null,
            // 总章数
            totalChapterQuantity: null,
            // 章节数组
            ChapterList: null,
            // 翻转标识符
            reverseflag: false,
            // 夜间日间标识符
            moduleFlag: true,
            // 大盒子DOM对象
            bookbox: null,
            // 点击的章节id
            uuid: null,
            // 章节内容
            BookContent: null,
            // 第一章id
            firstId: null,
            // 内容盒子DOM对象
            item: null,
            // 当前章节标题
            currentTitle: null,
            // 字体大小描述
            fontSizeDesc: "正常",
            // 当前章节下标(默认为1)
            currentPage: 1,
            // 历史id
            historyuuid: null,
            moreShow: false,
            // 分享
            showShare: false,
            options: [
                [
                    { name: "微信", icon: "wechat" },
                    { name: "朋友圈", icon: "wechat-moments" },
                    { name: "微博", icon: "weibo" },
                    { name: "QQ", icon: "qq" },
                ],
                [
                    { name: "复制链接", icon: "link" },
                    { name: "分享海报", icon: "poster" },
                    { name: "二维码", icon: "qrcode" },
                    { name: "小程序码", icon: "weapp-qrcode" },
                ],
            ],
        };
    },
    created() {
        // 接收书籍id
        this.BookId = this.$route.query.BookId;
        // 获取当前章节标题
        // this.currentTitle = localStorage.getItem("currentTitle");
        // 目录数据
        this.getCatalogueData();
        // 防止获取不到目录数据
        setTimeout(() => {
            // 获取阅读历史数组
            let readHistoryList = JSON.parse(localStorage.getItem("readHistoryList")) || [];
            if (readHistoryList.length > 0) {
                // 判断当前书籍是否在阅读历史数组中 在的话就用数组的章节id 不在就用第一章的id
                for (let i = 0; i < readHistoryList.length; i++) {
                    if (readHistoryList[i].BookId == this.BookId) {
                        //
                        //
                        //
                        // 保存历史章节id
                        this.historyuuid = readHistoryList[i].uuid;
                        //
                        if (this.ChapterList !== null) {
                            for (let j = 0; j < this.ChapterList.length; j++) {
                                if (this.ChapterList[j].uuid == this.historyuuid) {
                                    //
                                    // 更新章节id下标 防止点击上一章 下一章混乱
                                    this.currentPage = j + 1;
                                }
                            }
                        }

                        this.getChapterContent(this.BookId, this.historyuuid);
                        return;
                    }
                }
                this.getChapterContent(this.BookId, this.firstId);
            } else {
                this.getChapterContent(this.BookId, this.firstId);
            }
        }, 100);

        // 等待dom加载完成后
        // setTimeout(() => {
        //     this.$nextTick(() => {
        //         // 获取内容DOM对象
        //         //
        //     });
        // }, 100);
    },
    mounted() {
        // 监听页面滚动
        window.addEventListener("scroll", this.getbottom);

        setTimeout(() => {
            this.getDom();
        }, 1000);
    },

    destroyed() {
        // 清除监听
        window.removeEventListener("scroll", this.getbottom);
        // 存入离开页面时的书籍id以及章节下标
        // 获取阅读历史数组 没有则为空
        let readHistoryList = JSON.parse(localStorage.getItem("readHistoryList")) || [];

        if (readHistoryList.length > 0) {
            // 遍历阅读历史数组,判断是否有当前书籍id 没有就记录书籍id以及当前章节id
            for (let i = 0; i < readHistoryList.length; i++) {
                // 如果有这本书,就更新章节id
                if (readHistoryList[i].BookId == this.BookId) {
                    readHistoryList[i].uuid = this.ChapterList[this.currentPage - 1].uuid;
                    readHistoryList[i].chapter = "第" + Number(this.currentPage - 1) + "章";
                    (readHistoryList[i].title = this.ChapterList[this.currentPage - 1].title), localStorage.setItem("readHistoryList", JSON.stringify(readHistoryList));
                    // 当前章节标题
                    // localStorage.setItem("currentTitle", this.ChapterList[this.currentPage - 1].title);

                    return;
                }
            }
            readHistoryList.push({
                BookId: this.BookId,
                uuid: this.ChapterList[this.currentPage - 1].uuid,
                name: this.BookMsg[0].title,
                chapter: "第" + Number(this.currentPage - 1) + "章",
                title: this.ChapterList[this.currentPage - 1].title,
            });

            // 存入本地
            localStorage.setItem("readHistoryList", JSON.stringify(readHistoryList));
        } else {
            // 没有阅读数据
            // 把当前的阅读数据放进去
            readHistoryList.push({
                BookId: this.BookId,
                uuid: this.ChapterList[this.currentPage].uuid,
                name: this.BookMsg[0].title,
                chapter: "第" + Number(this.currentPage - 1) + "章",
                title: this.ChapterList[this.currentPage - 1].title,
            });

            // 存入本地
            localStorage.setItem("readHistoryList", JSON.stringify(readHistoryList));
        }
    },

    components: {
        LazyLoading,
    },
    methods: {
        // 获取相关dom对象
        getDom() {
            if (this.$refs.item !== undefined) {
                this.item = this.$refs.item[0];

                if (this.item == null) {
                    this.getDom();
                }
            }
        },
        // 下一章
        nextTChapter() {
            this.currentPage++;

            // 根据下标获取下一章节id
            let nextID = this.ChapterList[this.currentPage - 1].uuid;
            this.getChapterContent(this.BookId, nextID);
        },
        // 上一章
        previousChapter() {
            if (this.currentPage == 1) {
                Toast("已经是第一章了!");
            } else {
                this.currentPage--;
                // 根据下标获取上一章节id
                let previousID = this.ChapterList[this.currentPage - 1].uuid;
                this.getChapterContent(this.BookId, previousID);
            }
        },
        // 上下弹窗
        toggleShow() {
            this.show = !this.show;
        },
        Back() {
            this.$router.back();
        },
        // 弹出目录
        PopupCatalogue() {
            this.leftshow = true;
            if (this.leftshow) {
                this.show = false;
            }
        },
        // 弹出设置字体大小的弹窗
        setSize() {
            this.fontsizeShow = true;
            if (this.fontsizeShow) {
                // 弹出设置字体大小弹窗时,收起上下弹窗
                this.show = false;
            }
        },
        // 加大字体大小
        augmentSize() {
            if (this.item !== null) {
                if (this.item.style.fontSize == "" || this.item.style.fontSize == "16px") {
                    this.item.style.fontSize = "18px";
                    this.fontSizeDesc = "显眼";
                } else if (this.item.style.fontSize == "14px") {
                    this.item.style.fontSize = "16px";
                    this.fontSizeDesc = "正常";
                } else {
                    Toast("不可以再大啦!");
                }
            }
        },
        // 缩小字体
        minishSize() {
            if (this.item !== null) {
                if (this.item.style.fontSize == "" || this.item.style.fontSize == "16px") {
                    this.item.style.fontSize = "14px";
                    this.fontSizeDesc = "入微";
                } else if (this.item.style.fontSize == "18px") {
                    this.item.style.fontSize = "16px";
                    this.fontSizeDesc = "正常";
                } else {
                    Toast("不可以再小啦!");
                }
            }
        },
        // 目录倒序
        overturn() {
            this.ChapterList.reverse();
            // 翻转标识符
            this.reverseflag = !this.reverseflag;
        },
        // 夜间日间切换
        toggleModel() {
            this.moduleFlag = !this.moduleFlag;
            if (this.moduleFlag) {
                (this.$refs.bookbox.style.backgroundColor = "#beac88"), (this.$refs.bookbox.style.color = "#444");
            } else {
                (this.$refs.bookbox.style.backgroundColor = "black"), (this.$refs.bookbox.style.color = "#fff");
            }
        },
        // 点击获取章节id
        getuuid(BookId, uuid, needPay) {
            // 收起目录
            this.leftshow = false;
            // 保存章节id
            this.uuid = uuid;
            // 根据书籍id和章节id获取章节内容
            if (needPay) {
                Toast.fail("该章节为付费章节");
                return;
            }

            // 根据当前章节id获取当前下标
            for (let i = 0; i < this.ChapterList.length; i++) {
                if (this.uuid == this.ChapterList[i].uuid) {
                    this.currentPage = i + 1;
                }
            }
            this.getChapterContent(BookId, uuid);
        },
        // 目录数据
        getCatalogueData() {
            this.axios({
                method: "get",
                url: "reader/book/info.json",
                params: {
                    source_uuid: this.BookId,
                },
            })
                .then((res) => {
                    //
                    this.firstTitle = res.data.data.catalog[0].title;

                    this.BookMsg = [res.data.data.book];
                    //
                    // (this.BookMsg);
                    this.totalChapterQuantity = res.data.data.catalog.length;
                    this.ChapterList = res.data.data.catalog;

                    // 将付费章节修改为免费章节
                    // for (let i = 0; i < this.ChapterList.length; i++) {
                    //     this.ChapterList[i].needPay = false;
                    // }

                    // 第一章没有内容,删掉
                    // this.ChapterList.splice(0, 1);
                    // 第一章id
                    this.firstId = this.ChapterList[0].uuid;
                })
                .catch((err) => {
                    err;
                });
        },
        // 根据书籍id和章节id获取章节内容
        getChapterContent(BookId, uuid) {
            this.axios({
                method: "get",
                url: "reader/book/content.json",
                params: {
                    source_uuid: BookId,
                    content_uuid: uuid,
                },
            })
                .then((res) => {
                    if (res.data.code === -1) {
                        setTimeout(() => {
                            this.getChapterContent(this.BookId, this.firstId);
                        }, 10);
                    } else if (res.data.code === 0) {
                        // 获取当前章节标题
                        if (this.ChapterList !== null) {
                            this.currentTitle = this.ChapterList[this.currentPage - 1].title;
                        }
                        setTimeout(() => {
                            this.getDom();
                        }, 100);
                        this.BookContent = [res.data.data.content];
                        // 更换章节时页面回到顶部
                        document.documentElement.scrollTop = 0;
                    }
                })
                .catch((err) => {});
        },

        getbottom() {
            // 返回滚动条垂直滚动距离
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            // 返回该元素的像素高度，高度包含内边距（padding），不包含边框（border），外边距（margin）和滚动条
            let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // 返回该元素的像素高度，高度包含内边距（padding），不包含外边距（margin）、边框（border）
            let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            let numHeight = scrollTop + clientHeight;
            if (scrollHeight > clientHeight && numHeight > scrollHeight - 1) {
                // 下标加一
                this.currentPage++;
                // 通过下一章下标获取章节id
                //
                let nextID = this.ChapterList[this.currentPage - 1].uuid;
                this.getChapterContent(this.BookId, nextID);
            }
        },
        // 更多
        more() {
            // 弹出分享
            this.show = false;
            this.moreShow = true;
        },

        showshare() {
            this.moreShow = false;
            this.showShare = true;
        },
    },
    watch: {
        BookContent(newData, oldData) {
            // if (oldData == null) {
            //     this.getChapterContent(this.BoookId, this.firstId);
            // }
        },
    },
};
</script>

<style lang="less" scoped>
.bookcontent {
    width: 100%;

    // height: auto;
    // position: absolute;
    // position: fixed;

    // top: 0;
    // left: 0;
    // right: 0;
    // bottom: 0;
    // min-height: 667px;
    background-color: #beac88;
    position: absolute;
    .share {
        height: 50px;
        line-height: 50px;
        font-size: 18px;
        color: #000;
        font-family: "fangson";
        text-align: center;
    }
    .setFontSize {
        display: flex;
        align-items: center;
        font-size: 16px;
        .title {
            margin: 0 10px 0 10px;
        }
        .set {
            display: flex;
            .minus,
            .augment {
                border-radius: 0.26667rem;
                border: 0.02667rem solid #686969;
                width: 45px;
                text-align: center;
                background-color: green;
                color: #fff;
            }
            .text {
                min-width: 35px;
                margin: 0 10px 0 10px;
                font-weight: 550;
            }
        }
    }
    .isShowPopup {
        // width: 100%;
        min-height: 667px;
        padding: 1px;

        .item-box {
            .item {
                // height: auto;
                min-height: 667px;

                padding: 0 16px;
                font-size: 16px;
                user-select: none;
                text-shadow: 0 0 2px #000;
                // img {
                //     width: 100px;
                // }
                // .g-book {
                //     .m-mb {
                //         .m-content {
                //             .yd-fullscreen {
                //                 .full-screen {
                //                     height: 100px;
                //                 }
                //             }
                //         }
                //     }
                // }
                // .yd-fullscreen {
                //     width: 100px;
                // }
            }
        }
    }
    .catalogue-box {
        &::-webkit-scrollbar {
            display: none;
        }
        .ShowCatalogue {
            width: 90%;
            margin: 0 auto;
            font-size: 14px;
            // display: flex;
            // align-items: center;
            // overflow-y: auto;

            .Catalogue-item {
                border-bottom: 0.02667rem dashed #686969;
                height: 40px;
                line-height: 40px;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
        }
        .TopMsg {
            width: 100%;
            // position: fixed;
            // top: 0;
            .top {
                width: 90%;
                margin: 0 auto;
                display: flex;
                padding: 15px 0 0 0;
                .BookCover {
                    width: 65px;
                    height: 90px;
                }
                .name-author {
                    width: calc(100% - 65px);
                    height: 80px;
                    .name {
                        font-size: 16px;
                        margin: 20px 0 5px 20px;
                    }
                    .author {
                        margin: 0 0 0 20px;
                        color: #919292;
                    }
                }
            }
            .bottom {
                width: 90%;
                height: 40px;
                margin: 0 auto;
                display: flex;
                align-items: center;
                justify-content: space-between;
                .reverse {
                    width: 1.06667rem;
                    height: 20px;
                    border-radius: 0.26667rem;
                    border: 0.02667rem solid;
                    padding-left: 0.13333rem;
                    padding-right: 3px;
                    line-height: 20px;
                    color: #919292;
                }
                .totalChapterQuantity {
                    font-size: 14px;
                }
            }
        }
    }

    .operation {
        height: 55px;
        display: flex;
        justify-content: space-around;
        .Catalogue-box,
        .Font-box,
        .Pattern-box,
        .More-box {
            width: 25px;
            height: 100%;
            img {
                width: 100%;
                height: 50%;
            }
            .text {
                width: 35px;
                font-size: 14px;
                color: #686969;
            }
        }
    }
    .CurrentChapter {
        height: 0.8rem;
        width: 375px;
        font-size: 0.37333rem;
        text-align: center;
        line-height: 30px;
    }
    .progress-box {
        height: 40px;
        display: flex;
        align-items: center;
        margin: -20px 0 0 0;
        justify-content: space-around;
        .left,
        .right {
            font-size: 20px;
            color: #686969;
        }
        .slider {
            width: 250px;
        }
    }

    .Toptool {
        width: 100%;
        height: 100%;
        .arrow-left {
            font-size: 24px;
            margin: 10px 0 0 10px;
        }
    }
    ::v-deep {
        .van-overlay {
            background-color: rgba(0, 0, 0, 0);
        }
    }
}
</style>
